package com.campus.fitter;

import com.campus.response.ResponseResult;
import com.campus.response.ResultCode;
import com.campus.util.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Component
public class UserFitter extends OncePerRequestFilter {
    @Autowired
    private JWTUtil jwtUtil;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        String token = request.getHeader("token");
        ResponseResult<Object> responseResult=new ResponseResult<>(ResultCode.NO_LOGIN,null);
        String responseString=Objects.toString(responseResult);
        String url=request.getRequestURI();
        if (isUrl(url)){
            filterChain.doFilter(request,response);
            return;
        }
        try {
            Claims claims = jwtUtil.parserJwt(token);
            filterChain.doFilter(request,response);
        } catch (Exception e) {
            log.error("出现异常{}",ResultCode.NO_LOGIN.getMessage());
            response.getWriter().write(responseString);
        }


    }
    private boolean isUrl(String url){
        String baseUrl="/api/v1";
        if (url.equals(baseUrl+"/account/login")){
            return true;
        }
        if (url.contains(baseUrl+"/swagger-ui")){
            return true;
        }
        if (url.contains(baseUrl+"/api-docs")){
            return true;
        }
        return false;
    }
}
